﻿using CanDoo.Admin.Core.Identity;
using CanDoo.Oil.WebApi.Api.Results;
using Microsoft.Owin.Security;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Web.Http;
using CanDoo.Admin.Core.Contracts;
using CanDoo.Oil.Core.Contracts;
using CanDoo.Data;
using CanDoo.Oil.Core.DTOs;
using CanDoo.Core.Data.Extensions;
using CanDoo.Core.Security;
using CanDoo.Core.Logging;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using CanDoo.Extensions;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Linq;
using CanDoo.Core.Context;
using CanDoo.Oil.Core.Models;
using System.IO;
using System.Net.Http.Headers;
using System.Web.Hosting;
using CanDoo.Core.Data;
using System.Diagnostics;

//webapiConfig.Filters.Add(new Areas.Api.Filters.ValidationActionFilter());
//webapiConfig.Filters.Add(new Areas.Api.Filters.ApiExceptionFilterAttribute());

namespace CanDoo.Oil.WebApi.Areas.Api.Filters
{
    /// <summary>
    /// 1.1操作屏接口
    /// </summary>
    //[Authorize]
    [ApiExceptionFilterAttribute]
    [ValidationActionFilter]
    [OverrideAuthentication]
    [HostAuthentication(OAuthDefaults.AuthenticationType)]
    [RoutePrefix("api/pad")]
    [Description("操作屏Webapi接口")]
    public class PadController : ApiController
    {
        #region owin

        public IAuthenticationManager AuthenticationManager { get; private set; }//认证管理
        public SignInManager SignInManager { get; private set; }//登陆管理

        #endregion

        #region Manager

        public IPermissionManager PermissionManager { get; private set; }
        public IOperateLoger OperateLoger { get; set; }
        public IOperator Operator { get; set; }

        /// <summary>
        /// 售油机序列号
        /// </summary>
        public IOilSalesSerialNumContract OilSalesSerialNumContract { get; set; }
        public ICustomerContract CustomerContract { get; set; }//客户管理
        public IUserContract UserContract { get; set; }//用户管理

        /// <summary>
        /// Api操作日志
        /// </summary>
        public IAPIOperateLogContract APIOperateLogContract { get; set; }
        public IStoreActivityContract StoreActivityContract { get; set; }

        public IProductContract ProductContract { get; set; }

        /// <summary>
        /// 取油吗
        /// </summary>
        public IGetOilCodeContract GetOilCodeContract { get; set; }

        public IOilSerialNumContract OilSerialNumContract { get; set; }

        public IMediaADContract MediaADContract { get; set; }
        
        public IConfigContract ConfigContract { get; set; }

        public IMoneyChangeContract MoneyChangeContract { get; set; }

        public IAppUpdateContract AppUpdateContract { get; set; }

        public IOilSiteConfig sysStaticConfig { get; set; }

        public IDB DB { get; set; }
        
        #endregion

        #region 属性

        private string _PageCode;
        public string PageCode
        {
            get
            {
                if (string.IsNullOrEmpty(_PageCode))
                {
                    _PageCode = this.GetType().Name;
                }
                return _PageCode;
            }
        }

        private string _pageTitle;
        public string PageTitle
        {
            get
            {
                if (string.IsNullOrEmpty(_pageTitle))
                {
                    _pageTitle = this.GetType().ToDescription();
                }
                return _pageTitle;
            }
        }

        #endregion

        #region ctor

        public PadController(IAuthenticationManager authenticationManager
            , SignInManager signInManager
            , IPermissionManager permissionManager
            )
        {
            AuthenticationManager = authenticationManager;
            SignInManager = signInManager;
            PermissionManager = permissionManager;

            PermissionManager.PageCode = PageCode;
            PermissionManager.PageTitle = PageTitle;
        }

        #endregion

        [Route("GetPADVersion")]
        [Display(Name = "获取PAD版本信息")]
        [HttpPost]
        public async Task<HttpResponseMessage> GetPADVersion()
        {
            var host = "http://" + Request.RequestUri.Host;

            VersionInfo versionInfo = AppUpdateContract.GetPADVersion(host);

            //OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode:"GetVersion",pagecode:this.PageCode,powerName: "获取版本信息",pageTitle:this.PageTitle,creatNewIfNotExists:true);
            //OperateLoger.InputMessage = "";
            //OperateLoger.OperationResult = OperationResult.Success;

            var result = new ApiResult<VersionInfo>();
            result.Data = versionInfo;

            //OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
            //await OperateLoger.SaveLogAsync();
            return Request.CreateResponse(true ? HttpStatusCode.OK : HttpStatusCode.BadRequest, result);
        }

        [Route("GetMediaVersion")]
        [Display(Name = "获取媒体版本信息")]
        [HttpPost]
        public async Task<HttpResponseMessage> GetMediaVersion()
        {
            var host = "http://" + Request.RequestUri.Host;

            VersionInfo versionInfo = AppUpdateContract.GetMediaVersion(host);

            //OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode: "GetVersion", pagecode: this.PageCode, powerName: "获取版本信息", pageTitle: this.PageTitle, creatNewIfNotExists: true);
            //OperateLoger.InputMessage = "";
            //OperateLoger.OperationResult = OperationResult.Success;

            var result = new ApiResult<VersionInfo>();
            result.Data = versionInfo;

            //OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
            //await OperateLoger.SaveLogAsync();
            return Request.CreateResponse(true ? HttpStatusCode.OK : HttpStatusCode.BadRequest, result);
        }

        [Route("GetCustomerInfo")]
        [Display(Name = "获取用户余额")]
        [HttpPost]
        public async Task<HttpResponseMessage> GetCustomerInfo(CustomerKeyInfo keyInfo)
        {
            if (keyInfo == null)
                throw new ArgumentException(nameof(keyInfo) + "不能为空");

            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode: "GetCustomerInfo", pagecode: this.PageCode, powerName: "获取用户余额", pageTitle: this.PageTitle, creatNewIfNotExists: true);
            OperateLoger.InputMessage = JsonConvert.SerializeObject(keyInfo);

            var result = new ApiResult<CustomerApiInfo>();
            result.Data = CustomerContract.GetByCardNo(keyInfo.CardNo);
            OperateLoger.OperationResult = OperationResult.Success;
            
            OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
            await OperateLoger.SaveLogAsync();
            return Request.CreateResponse(true ? HttpStatusCode.OK : HttpStatusCode.BadRequest, result);
        }

        /// <summary>
        /// 1.1.1设备绑定 新售油机接入门店时，门店与设备绑定
        /// 测试数据:   
        /// {"storeNo":"333333","terminalNo":"","type":"1234567","sn":""}
        /// {"storeNo":"只能使用一次","terminalNo":"必填，但是不能重复，不能为空","type":"机器型号的条码","sn":"必填，不能重复"}
        /// </summary>
        /// <param name="deviceInfo"></param>
        /// <returns></returns>
        [Route("BindDevice")]
        [Display(Name = "设备绑定")]
        public async Task<HttpResponseMessage> BindDevice(DeviceInfo deviceInfo)
        {
            if (deviceInfo == null)
                throw new ArgumentException(nameof(deviceInfo) + "不能为空");
            if (string.IsNullOrEmpty(deviceInfo.storeNo))
                throw new ArgumentException(nameof(deviceInfo.storeNo) + "不能为空");
            if (string.IsNullOrEmpty(deviceInfo.sn))
                throw new ArgumentException(nameof(deviceInfo.sn) + "不能为空");
            if (string.IsNullOrEmpty(deviceInfo.type))
                throw new ArgumentException(nameof(deviceInfo.type) + "不能为空");

            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode: "BindDevice", pagecode: this.PageCode, powerName: "设备绑定", pageTitle: this.PageTitle, creatNewIfNotExists: true);
            //OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo();
            OperateLoger.InputMessage = JsonConvert.SerializeObject(deviceInfo);

            OperationResult or = await OilSalesSerialNumContract.BindDeviceAsync(deviceInfo);
            OperateLoger.OperationResult = or;

            var result = new ApiResult<DeviceInfo>();          

            result.Data = deviceInfo;
            if (or.Succeeded)
            {
                result.ResultType = ApiResultType.sucess;
            }
            else
            {
                result.ResultType = ApiResultType.fail;
            }
            result.Message = or.Message;
            result.InnerMessage = or.Message;

            OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);

            await OperateLoger.SaveLogAsync();

            return Request.CreateResponse(or.Succeeded ? HttpStatusCode.OK : HttpStatusCode.BadRequest, result);
        }

        /// <summary>
        /// 1.1.2获取售油配置信息 Pad端从后台获取售油机配置信息
        /// 测试数据: {"storeNo" : "1", "terminalNo" : "1"}
        /// </summary>
        /// <param name="keyInfo">门店号 终端号</param>
        /// <returns></returns>
        [Display(Name = "获取售油配置信息")]
        [Route("PullSellingConfigInfo")]
        public async Task<HttpResponseMessage> PullSellingConfigInfo(TerminalKeyInfo keyInfo)
        {
            //OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo();
            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode: "PullSellingConfigInfo", pagecode: this.PageCode, powerName: "获取售油配置信息", pageTitle: this.PageTitle, creatNewIfNotExists: true);
            OperateLoger.InputMessage = JsonConvert.SerializeObject(keyInfo);

            ApiResult<SellingConfigInfo> result = new ApiResult<SellingConfigInfo>();

            SellingConfigInfo config = await OilSalesSerialNumContract.GetSellingConfigInfoAsync(keyInfo);
            if (config == null)
            {
                result.ResultType = ApiResultType.fail;
                result.InnerMessage = "无法找到数据,可能门店号或终端号有误";
                OperateLoger.OperationResult = new OperationResult(OperationResultType.QueryNull);
            }
            else
            {
                result.ResultType = ApiResultType.sucess;
                result.Data = config;
                result.InnerMessage = "成功获取售油配置信息";
                OperateLoger.OperationResult = OperationResult.Success;
            }

            OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
            await OperateLoger.SaveLogAsync();
            return Request.CreateResponse(result.ResultType == ApiResultType.sucess ? HttpStatusCode.OK : HttpStatusCode.BadRequest, result);
        }

        /// <summary>
        /// 1.1.3取油码取油: 自助取油，用户输入取油码，后台验证有效性。 {"oilCode": "1","terminalNo": "1"}
        /// </summary>
        /// <param name="code">取油码代码</param>
        /// <returns>取油码信息</returns>
        [Route("PullOilCodeInfo")]
        [Display(Name = "取油码取油")]
        public async Task<HttpResponseMessage> PullOilCodeInfo(OilCodeCode code)
        {
            //OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo();
            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode: "PullOilCodeInfo", pagecode: this.PageCode, powerName: "取油码取油", pageTitle: this.PageTitle, creatNewIfNotExists: true);
            OperateLoger.InputMessage = JsonConvert.SerializeObject(code);
            OperateLoger.OperationResult = OperationResult.Success;
            
            ApiResult<OilCodeInfo> result = new ApiResult<OilCodeInfo>();

            OilSalesSerialNum oilSalesSerialNum = await OilSalesSerialNumContract.GetByTerminalNoAsync(code.terminalNo);
            if (oilSalesSerialNum == null)
            {
                result.ResultType = ApiResultType.fail;
                result.InnerMessage = $"找不到终端号为{code.terminalNo}的售油机.";
            }
            else
            {
                try
                {
                    OilCodeInfo data = await GetOilCodeContract.GetOilCodeAsync(code.oilCode, code.terminalNo);
                    if (data == null)
                    {
                        result.ResultType = ApiResultType.fail;
                        result.InnerMessage = "取油码对应记录不存在.";
                    }
                    else
                    {
                        result.Data = data;
                    }
                }
                catch(Exception ex)
                {
                    result.ResultType = ApiResultType.fail;
                    result.InnerMessage = ex.ToString();
                }
            }

            OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
            OperateLoger.OperationResult = result.ResultType == ApiResultType.sucess ? OperationResult.Success : new OperationResult(OperationResultType.Error, result.InnerMessage);
            await OperateLoger.SaveLogAsync();

            result.ResultType = ApiResultType.sucess;

            return Request.CreateResponse(result.ResultType == ApiResultType.sucess ? HttpStatusCode.OK : HttpStatusCode.BadRequest, result);
        }

        /// <summary>
        /// 1.1.4取油码取油状态上报:  终端完成取油操作时，将取油状态上报至后台
        /// </summary>
        /// <param name="status">取油状态信息</param>
        /// <returns>操作结果</returns>
        [Display(Name = "取油码取油状态上报")]
        [Route("PushOilCodeStatus")]
        public async Task<HttpResponseMessage> PushOilCodeStatus(OilCodeStatus status)
        {
            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode: "PushOilCodeStatus", pagecode: this.PageCode, powerName: "取油码取油状态上报", pageTitle: this.PageTitle, creatNewIfNotExists: true);
            OperateLoger.InputMessage = JsonConvert.SerializeObject(status);
            OperateLoger.OperationResult = OperationResult.Success;

            ApiResult result = new ApiResult();
            OperationResult or = await APIOperateLogContract.AddOilCodeStatusAsync(status);
            if (or.Succeeded == false)
            {
                result.ResultType = ApiResultType.fail;
                result.InnerMessage = or.Message;
                result.Message = or.Message;
            }
            else
            {
                result.ResultType = ApiResultType.sucess;//操作成功信息编号
                result.Message = "操作成功";           //操作成功描述信息
                result.InnerMessage = "状态上报成功";      //操作成功信息
            }

            OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
            OperateLoger.OperationResult = result.ResultType == ApiResultType.sucess ? OperationResult.Success : new OperationResult(OperationResultType.Error, result.InnerMessage);
            await OperateLoger.SaveLogAsync();
            return Request.CreateResponse(result.ResultType == ApiResultType.sucess ? HttpStatusCode.OK:HttpStatusCode.BadRequest, result);
        }



        /// <summary>
        /// 1.1.5 本店活动:输入门店相关信息去后台请求活动详情
        /// </summary>
        /// <param name="storeNoInfo">店铺号</param>
        /// <returns></returns>
        [Route("PullStoreCampaign")]
        public async Task<HttpResponseMessage> PullStoreCampaign(StoreNoInfo storeNoInfo)
        {
            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode: "PullStoreCampaign", pagecode: this.PageCode, powerName: "本店活动", pageTitle: this.PageTitle, creatNewIfNotExists: true);
            //OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo();
            OperateLoger.InputMessage = JsonConvert.SerializeObject(storeNoInfo);
            OperateLoger.OperationResult = OperationResult.Success;

            string storeNo = storeNoInfo.StoreNo;
            StoreCampaign[] data = await StoreActivityContract.GetByStoreNoAsync(storeNo);//找不到也没关系

            ApiResult<StoreCampaign[]> result = new ApiResult<StoreCampaign[]>();
            if (data == null)
            {
                result.ResultType = ApiResultType.fail;
                result.InnerMessage = "找不到任何活动信息";
            }
            else
            {
                result.Data = data;
                result.ResultType = ApiResultType.sucess;
                result.Message = "操作成功";
                result.InnerMessage = "成功获取本店活动";
            }

            OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
            OperateLoger.OperationResult = result.ResultType == ApiResultType.sucess ? OperationResult.Success : new OperationResult(OperationResultType.Error, result.InnerMessage);
            await OperateLoger.SaveLogAsync();
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

        /// <summary>
        /// 1.1.6 门店介绍 : {  "StoreNo": "123123"}
        /// </summary>
        /// <param name="storeNoInfo">门店号</param>
        /// <returns>门店基本信息介绍</returns>
        [Route("PullStoreIntroduction")]
        public async Task<HttpResponseMessage> PullStoreIntroduction(StoreNoInfo storeNoInfo)
        {
            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode: "PullStoreIntroduction", pagecode: this.PageCode, powerName: "门店介绍", pageTitle: this.PageTitle, creatNewIfNotExists: true);
            OperateLoger.InputMessage = JsonConvert.SerializeObject(storeNoInfo);
            OperateLoger.OperationResult = OperationResult.Success;

            ApiResult<StoreIntroduction> result = new ApiResult<StoreIntroduction>();

            string storeNo = storeNoInfo.StoreNo;
            StoreIntroduction data = CustomerContract.GetStoreIntroductionByStoreNo(storeNo);
            if (data == null)
            {
                result.ResultType = ApiResultType.fail;
                result.InnerMessage = "无法找到数据,可能门店号有误";
            }
            else
            {
                result.Data = data;
                result.ResultType = ApiResultType.sucess;
                result.Message = "操作成功";
                result.InnerMessage = "成功获取门店基本信息介绍";
            }
            OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
            OperateLoger.OperationResult = result.ResultType == ApiResultType.sucess ? OperationResult.Success : new OperationResult(OperationResultType.Error, result.InnerMessage);
            await OperateLoger.SaveLogAsync();

            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

        /// <summary>
        /// 1.1.7 会员取油申请
        /// </summary>
        /// <param name="oilTankUserInfo">会员取油信息</param>
        /// <returns>是否允许取油</returns>
        [Route("PullOilTankByUser")]
        public async Task<HttpResponseMessage> PullOilTankByUser(OilTankUserInfo oilTankUserInfo)
        {
            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode: "PullOilTankByUser", pagecode: this.PageCode, powerName: "会员取油申请", pageTitle: this.PageTitle, creatNewIfNotExists: true);
            OperateLoger.InputMessage = JsonConvert.SerializeObject(oilTankUserInfo);
            OperateLoger.OperationResult = OperationResult.Success;

            ApiResult result = new ApiResult();

            OperationResult or = CustomerContract.CanTakeOil(oilTankUserInfo);
            result.Data = oilTankUserInfo;
            if (or.Succeeded == false)
            {
                result.ResultType = ApiResultType.error;//操作成功信息编号
                result.Message = or.Message;           //操作成功描述信息
                result.InnerMessage = or.Message;      //操作成功信息
            }
            else
            {
                result.ResultType = ApiResultType.sucess;
                result.Message = "操作成功";
                result.InnerMessage = "可以取油";
            }

            OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
            OperateLoger.OperationResult = result.ResultType == ApiResultType.sucess ? OperationResult.Success : new OperationResult(OperationResultType.Error, result.InnerMessage);
            await OperateLoger.SaveLogAsync();
            return Request.CreateResponse(result.ResultType == ApiResultType.sucess ? HttpStatusCode.OK : HttpStatusCode.BadRequest, result);
        }

        /// <summary>
        /// 1.1.8会员取油成功状态上报 : 会员取油成功后，将取油情况上报后台
        /// </summary>
        /// <param name="oilTankStatus">取油请求报文</param>
        /// <returns>操作结果</returns>
        [Route("PushOilTankStatusByUser")]
        public async Task<HttpResponseMessage> PushOilTankStatusByUser(OilTankStatus oilTankStatus)
        {
            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode: "PushOilTankStatusByUser", pagecode: this.PageCode, powerName: "会员取油成功状态上报", pageTitle: this.PageTitle, creatNewIfNotExists: true);
            OperateLoger.InputMessage = JsonConvert.SerializeObject(oilTankStatus);
            OperateLoger.OperationResult = OperationResult.Success;

            ApiResult result = new ApiResult();

            OperationResult or = APIOperateLogContract.AddOilTankStatus(oilTankStatus);
            if (or.Succeeded == false)
            {
                result.ResultType = ApiResultType.error;//操作成功信息编号
                result.Message = or.Message;           //操作成功描述信息
                result.InnerMessage = or.Message;      //操作成功信息
            }
            else
            {
                result.ResultType = ApiResultType.sucess;
                result.Message = "操作成功";
                result.InnerMessage = "操作成功";
            }

            OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
            OperateLoger.OperationResult = result.ResultType == ApiResultType.sucess ? OperationResult.Success : new OperationResult(OperationResultType.Error, result.InnerMessage);
            await OperateLoger.SaveLogAsync();
            return Request.CreateResponse(result.ResultType == ApiResultType.sucess ? HttpStatusCode.OK : HttpStatusCode.BadRequest, result);
        }

        /// <summary>
        /// 1.1.8--1 会员取油成功状态批量上报 : 会员取油成功后，将取油情况上报后台
        /// </summary>
        /// <param name="oilTankStatus">取油请求报文</param>
        /// <returns>操作结果</returns>
        [Route("PushOilTankStatusListByUser")]
        public async Task<HttpResponseMessage> PushOilTankStatusListByUser(List<OilTankStatus> oilTankStatusList)
        {
            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode: "PushOilTankStatusByUser", pagecode: this.PageCode, powerName: "会员取油成功状态上报", pageTitle: this.PageTitle, creatNewIfNotExists: true);
            OperateLoger.InputMessage = JsonConvert.SerializeObject(oilTankStatusList);
            OperateLoger.OperationResult = OperationResult.Success;

            ApiResult result = new ApiResult();

            OperationResult or = DB.Save(()=> {
                foreach (var item in oilTankStatusList)
                {
                    APIOperateLogContract.AddOilTankStatus(item);
                }
                return OperationResult.Success;
            });

            if (or.Succeeded == false)
            {
                result.ResultType = ApiResultType.error;//操作成功信息编号
                result.Message = or.Message;           //操作成功描述信息
                result.InnerMessage = or.Message;      //操作成功信息
            }
            else
            {
                result.ResultType = ApiResultType.sucess;
                result.Message = "操作成功";
                result.InnerMessage = "操作成功";
            }

            OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
            OperateLoger.OperationResult = result.ResultType == ApiResultType.sucess ? OperationResult.Success : new OperationResult(OperationResultType.Error, result.InnerMessage);
            await OperateLoger.SaveLogAsync();
            return Request.CreateResponse(result.ResultType == ApiResultType.sucess ? HttpStatusCode.OK : HttpStatusCode.BadRequest, result);
        }
        
        /// <summary>
        /// 1.1.10 换油桶请求{ "epc": "2234576",  "tid": "1",  "storeNo": "123123",  "terminalNo": "1",  "oilPort": 1}
        /// </summary>
        /// <param name="oilDrumReqInfo"></param>
        /// <returns></returns>
        [Display(Name = "换油桶请求")]
        [Route("PushChangeOilDrumReq")]
        public async Task<HttpResponseMessage> PushChangeOilDrumReq(OilDrumReqInfo oilDrumReqInfo)
        {
            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode: "PushChangeOilDrumReq", pagecode: this.PageCode, powerName: "换油桶请求", pageTitle: this.PageTitle, creatNewIfNotExists: true);
            OperateLoger.InputMessage = JsonConvert.SerializeObject(oilDrumReqInfo);
            OperateLoger.OperationResult = OperationResult.Success;

            var result = new ApiResult<OilDrumReqInfo>();

            //TODO:1.1.14换油桶请求,向后台申请更换油桶操作 这里的业务怎么处理?@zyf
            //TODO:1.1.14APIOPERATERLOG表操作掉 查询油品序列号 如果存在并且所属客户没有写掉 就返回成功 否则返回失败

            OperationResult or = await OilSerialNumContract.ChangeOilDrumReq(oilDrumReqInfo);//= APIOperateLogContract.AddOilTankStatus(oilDrumReqInfo);
            result.Data = oilDrumReqInfo;
#if TEST
            result.ResultType = ApiResultType.sucess;
            result.Message = "TEST环境，操作成功" + or.Message;
            result.InnerMessage = "TEST环境，操作成功" + or.Message;
#else
            if (or.Succeeded == false)
            {
                result.ResultType = ApiResultType.error;//操作成功信息编号
                result.Message = or.Message;           //操作成功描述信息
                result.InnerMessage = or.Message;      //操作成功信息
            }
            else
            {
                result.ResultType = ApiResultType.sucess;
                result.Message = "操作成功";
                result.InnerMessage = "操作成功";
            }
#endif

            OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
            OperateLoger.OperationResult = result.ResultType == ApiResultType.sucess ? new OperationResult(OperationResultType.Success, result.InnerMessage) : new OperationResult(OperationResultType.Error, result.InnerMessage);
            await OperateLoger.SaveLogAsync();
            return Request.CreateResponse(result.ResultType == ApiResultType.sucess ? HttpStatusCode.OK : HttpStatusCode.BadRequest, result);
        }

        /// <summary>
        /// 1.1.11 更换油桶状态上报 向后台上报油桶更换结果{  "epc": "2234576",  "tid": "sample string 2",  "storeNo": "123123",  "terminalNo": "1",  "oilPort":1,  "type": 1,  "operation": "sample string 7",  "operationTime": "2016-08-11T19:10:41.3816775+08:00",  "status": 1}
        /// </summary>
        /// <param name="changeOilDrumInfo"></param>
        /// <returns></returns>
        [Display(Name = "向后台上报油桶更换结果")]
        [Route("PushChangeOilDrumInfo")]
        public async Task<HttpResponseMessage> PushChangeOilDrumInfo(ChangeOilDrumInfo changeOilDrumInfo)
        {
            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode: "PushChangeOilDrumInfo", pagecode: this.PageCode, powerName: "向后台上报油桶更换结果", pageTitle: this.PageTitle, creatNewIfNotExists: true);
            OperateLoger.InputMessage = JsonConvert.SerializeObject(changeOilDrumInfo);
            OperateLoger.OperationResult = OperationResult.Success;

            var result = new ApiResult<ChangeOilDrumInfo>();

            //TODO:1.1.15更换油桶状态上报 向后台上报油桶更换结果@zyf
            //TODO:1.1.15APIOPERATERLOG表操作掉 然后油的序列号 把所属客户写好  这样就知道 这个油在哪个机器上销售了
            //throw new NotImplementedException();
            OperationResult or = await OilSerialNumContract.ChangeOilDrumInfo(changeOilDrumInfo);

            result.Data = changeOilDrumInfo;
            if (or.Succeeded == false)
            {
                result.ResultType = ApiResultType.error;//操作成功信息编号
                result.Message = or.Message;           //操作成功描述信息
                result.InnerMessage = or.Message;      //操作成功信息
            }
            else
            {
                result.ResultType = ApiResultType.sucess;
                result.Message = "操作成功";
                result.InnerMessage = "操作成功";
            }


            OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
            OperateLoger.OperationResult = result.ResultType == ApiResultType.sucess ? OperationResult.Success : new OperationResult(OperationResultType.Error, result.InnerMessage);
            await OperateLoger.SaveLogAsync();
            return Request.CreateResponse(result.ResultType == ApiResultType.sucess ? HttpStatusCode.OK : HttpStatusCode.BadRequest, result);
        }

        /// <summary>
        /// 1.1.12清洗操作记录查询 根据清洗时间、清洗管道、清洗门店、清洗终端编号，查询最近一次清洗记录
        /// </summary>
        /// <param name="cleanRecordReq"></param>
        /// <returns></returns>
        [Display(Name = "清洗操作记录查询")]
        [Route("PullLastCleanRecord")]
        public async Task<HttpResponseMessage> PullLastCleanRecord(CleanRecordReq cleanRecordReq)
        {
            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode: "PullLastCleanRecord", pagecode: this.PageCode, powerName: "清洗操作记录查询", pageTitle: this.PageTitle, creatNewIfNotExists: true);
            OperateLoger.InputMessage = JsonConvert.SerializeObject(cleanRecordReq);
            OperateLoger.OperationResult = OperationResult.Success;

            var result = new ApiResult<CleanRecordReqInfo>();

            //OperationResult or = OperationResult.Success;
            OperationResult<CleanRecordReqInfo> or = APIOperateLogContract.GetLastCleanRecord(cleanRecordReq);
            if (or.Succeeded == false)
            {
                result.ResultType = ApiResultType.error;//操作成功信息编号
                result.InnerMessage = or.Message;      //操作成功信息
                result.Data = or.Data;      //操作成功信息
            }
            else
            {
                result.Data = or.Data;
                result.ResultType = ApiResultType.sucess;
                result.InnerMessage = "操作成功";
            }

            OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
            OperateLoger.OperationResult = result.ResultType == ApiResultType.sucess ? OperationResult.Success : new OperationResult(OperationResultType.Error, result.InnerMessage);
            await OperateLoger.SaveLogAsync();
            return Request.CreateResponse(result.ResultType == ApiResultType.sucess ? HttpStatusCode.OK : HttpStatusCode.BadRequest, result);
        }

        /// <summary>
        /// 1.1.13清洗操作记录上传 将清洗操作记录上传到后台
        /// </summary>
        /// <param name="cleanRecordRspInfo"></param>
        /// <returns></returns>
        [Display(Name = "清洗操作记录上传")]
        [Route("PullCleanRecord")]
        public async Task<HttpResponseMessage> PullCleanRecord(CleanRecordRepInfo cleanRecordRspInfo)
        {
            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode: "PullCleanRecord", pagecode: this.PageCode, powerName: "清洗操作记录上传", pageTitle: this.PageTitle, creatNewIfNotExists: true);
            OperateLoger.InputMessage = JsonConvert.SerializeObject(cleanRecordRspInfo);
            OperateLoger.OperationResult = OperationResult.Success;

            var result = new ApiResult();

            //TODO:1.1.18清洗操作记录上传 将清洗操作记录上传到后台@zyf
            //TODO:1.1.18把清洗记录记录到APIOperateLog表就行了
            OperationResult or = APIOperateLogContract.AddCleanRecord(cleanRecordRspInfo);
            if (or.Succeeded == false)
            {
                result.ResultType = ApiResultType.error;//操作成功信息编号
                result.InnerMessage = or.Message;      //操作成功信息
                result.Message = or.Message;
            }
            else
            {
                result.ResultType = ApiResultType.sucess;
                result.InnerMessage = "操作成功";
                result.Message = or.Message;
            }

            OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
            OperateLoger.OperationResult = result.ResultType == ApiResultType.sucess ? OperationResult.Success : new OperationResult(OperationResultType.Error, result.InnerMessage);
            await OperateLoger.SaveLogAsync();
            return Request.CreateResponse(result.ResultType == ApiResultType.sucess ? HttpStatusCode.OK : HttpStatusCode.BadRequest, result);
        }

        /// <summary>
        /// 1.1.14管理员调试出油记录上传   管理员在登录状况下，调试出油记录上传
        /// </summary>
        /// <param name="debugOilRecord">调试出油记录</param>
        /// <returns></returns>
        [Route("PushDebugOilRecord")]
        [Display(Name = "管理员调试出油记录上传")]
        public async Task<HttpResponseMessage> PushDebugOilRecord(DebugOilRecord debugOilRecord)
        {
            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode: "PushDebugOilRecord", pagecode: this.PageCode, powerName: "管理员调试出油记录上传", pageTitle: this.PageTitle, creatNewIfNotExists: true);
            OperateLoger.InputMessage = JsonConvert.SerializeObject(debugOilRecord);
            OperateLoger.OperationResult = OperationResult.Success;

            var result = new ApiResult();

            //TODO:1.1.19管理员调试出油记录上传 这里的业务怎么处理? @zyf
            //TODO:1.1.19记录到APIOperateLog表就行了
            OperationResult or = APIOperateLogContract.AddDebugOilRecord(debugOilRecord);
            if (or.Succeeded == false)
            {
                result.ResultType = ApiResultType.error;//操作成功信息编号
                result.InnerMessage = or.Message;      //操作成功信息
                result.Message = or.Message;
            }
            else
            {
                result.ResultType = ApiResultType.sucess;
                result.InnerMessage = "操作成功";
                result.Message = or.Message;
            }

            OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
            OperateLoger.OperationResult = result.ResultType == ApiResultType.sucess ? OperationResult.Success : new OperationResult(OperationResultType.Error, result.InnerMessage);
            await OperateLoger.SaveLogAsync();
            return Request.CreateResponse(result.ResultType == ApiResultType.sucess ? HttpStatusCode.OK : HttpStatusCode.BadRequest, result);
        }

        /// <summary>
        /// 1.1.15 状态上报：终端门锁状态、服务员卡余额、机器运行状态（包括电机状态、称重仪状态媒体屏状态等记录）
        /// </summary>
        /// <param name="statusInfo">状态信息</param>
        /// <returns></returns>
        [Route("PushStatus")]
        [Display(Name = "状态上报")]
        public async Task<HttpResponseMessage> PushStatus(StatusInfo statusInfo)
        {
            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode: "PushStatus", pagecode: this.PageCode, powerName: "状态上报", pageTitle: this.PageTitle, creatNewIfNotExists: true);
            OperateLoger.InputMessage = JsonConvert.SerializeObject(statusInfo);
            OperateLoger.OperationResult = OperationResult.Success;

            var result = new ApiResult();

            //throw new NotImplementedException();
            OperationResult or = OperationResult.Success;
            or = APIOperateLogContract.AddStatusInfo(statusInfo);
            if (or.Succeeded == false)
            {
                result.ResultType = ApiResultType.error;//操作成功信息编号
                result.InnerMessage = or.Message;      //操作成功信息
                result.Message = or.Message;
            }
            else
            {
                result.ResultType = ApiResultType.sucess;
                result.InnerMessage = "操作成功";
                result.Message = or.Message;
            }

            OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
            OperateLoger.OperationResult = result.ResultType == ApiResultType.sucess ? OperationResult.Success : new OperationResult(OperationResultType.Error, result.InnerMessage);
            await OperateLoger.SaveLogAsync();
            return Request.CreateResponse(result.ResultType == ApiResultType.sucess ? HttpStatusCode.OK : HttpStatusCode.BadRequest, result);
        }
        //1.1.16 媒体门店登录 根据媒体门店号和媒体终端号登录

        /// <summary>
        /// 1.1.17 查询媒体列表 输入媒体门店id、终端id查询媒体列表
        /// </summary>
        /// <param name="terminalKeyInfo">终端信息</param>
        /// <returns></returns>
        [Route("PullMediaList")]
        [Display(Name = "媒体列表")]
        public async Task<HttpResponseMessage> PullMediaList(TerminalKeyInfo terminalKeyInfo)
        {
            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode: "PullMediaList", pagecode: this.PageCode, powerName: "媒体列表", pageTitle: this.PageTitle, creatNewIfNotExists: true);
            OperateLoger.InputMessage = JsonConvert.SerializeObject(terminalKeyInfo);
            OperateLoger.OperationResult = OperationResult.Success;

            var result = new ApiResult<List<MediaInfo>>();

            
            //throw new NotImplementedException();
            var or = OperationResult.Success;
            List<MediaInfo> list = MediaADContract.GetByTerminal(terminalKeyInfo);
            if (or.Succeeded == false)
            {
                result.ResultType = ApiResultType.error;//操作成功信息编号
                result.Message = or.Message;      //操作成功信息
                result.InnerMessage = or.Message;      //操作成功信息
            }
            else
            {
                foreach (var item in list)
                {
                    item.mediaUrl = this.Url.Content(item.mediaUrl);
                }
                result.ResultType = ApiResultType.sucess;
                result.InnerMessage = "操作成功";
                result.Message = or.Message;
                result.Data = list;
            }

            OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
            OperateLoger.OperationResult = result.ResultType == ApiResultType.sucess ? OperationResult.Success : new OperationResult(OperationResultType.Error, result.InnerMessage);
            //await OperateLoger.SaveLogAsync();
            return Request.CreateResponse(result.ResultType == ApiResultType.sucess ? HttpStatusCode.OK : HttpStatusCode.BadRequest, result);
        }

        /// <summary>
        /// 1.1.18 下载媒体
        /// </summary>
        /// <param name="mediaUrl">mediaUrl</param>
        /// <returns></returns>
        [Route("DownloadMediaByUrl")]
        [Display(Name = "下载媒体")]
        public HttpResponseMessage DownloadMediaByUrl(string mediaUrl)
        {
            HttpResponseMessage result = null;

            DirectoryInfo directoryInfo = new DirectoryInfo(HostingEnvironment.MapPath("~/App_Data/" + mediaUrl));
            FileInfo foundFileInfo = directoryInfo.GetFiles().Where(x => x.Name == mediaUrl).FirstOrDefault();
            if (foundFileInfo != null)
            {
                FileStream fs = new FileStream(foundFileInfo.FullName, FileMode.Open);

                result = new HttpResponseMessage(HttpStatusCode.OK);
                result.Content = new StreamContent(fs);
                result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                result.Content.Headers.ContentDisposition.FileName = foundFileInfo.Name;
            }
            else
            {
                result = new HttpResponseMessage(HttpStatusCode.NotFound);
            }

            return result;
        }

        /// <summary>
        /// 1.1.18 IC卡充值请求
        /// </summary>
        /// <param name="rechargeReqInfo"></param>
        /// <returns></returns>
        [Display(Name = "充值请求")]
        [Route("PullRechargeReq")]
        public async Task<HttpResponseMessage> PullRechargeReq(RechargeReqInfo rechargeReqInfo)
        {
            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode: "PullRechargeReq", pagecode: this.PageCode, powerName: "充值请求", pageTitle: this.PageTitle, creatNewIfNotExists: true);
            OperateLoger.InputMessage = JsonConvert.SerializeObject(rechargeReqInfo);
            OperateLoger.OperationResult = OperationResult.Success;

            var result = new ApiResult();



            //TODO:1.1.14换油桶请求,向后台申请更换油桶操作 这里的业务怎么处理?@zyf
            //TODO:1.1.14APIOPERATERLOG表操作掉 查询油品序列号 如果存在并且所属客户没有写掉 就返回成功 否则返回失败

            //OperationResult or = await OilSerialNumContract.ChangeOilDrumReq(oilDrumReqInfo);//= APIOperateLogContract.AddOilTankStatus(oilDrumReqInfo);
            OperationResult or = MoneyChangeContract.RechargeReq(rechargeReqInfo);
            //result.Data = oilDrumReqInfo;
            if (or.Succeeded == false)
            {
                result.ResultType = ApiResultType.error;//操作成功信息编号
                result.Message = or.Message;           //操作成功描述信息
                result.InnerMessage = or.Message;      //操作成功信息
            }
            else
            {
                result.ResultType = ApiResultType.sucess;
                result.Message = "操作成功";
                result.InnerMessage = "操作成功";
            }

            OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
            OperateLoger.OperationResult = result.ResultType == ApiResultType.sucess ? new OperationResult(OperationResultType.Success, result.InnerMessage) : new OperationResult(OperationResultType.Error, result.InnerMessage);
            await OperateLoger.SaveLogAsync();
            return Request.CreateResponse(result.ResultType == ApiResultType.sucess ? HttpStatusCode.OK : HttpStatusCode.BadRequest, result);
        }

        /// <summary>
        /// 银联设备充值记录上传
        /// </summary>
        /// <param name="rechargeRspInfo"></param>
        /// <returns></returns>
        [Display(Name = "充值记录上传")]
        [Route("PushRechargeInfo")]
        public async Task<HttpResponseMessage> PushRechargeInfo(RechargeRspInfo rechargeRspInfo)
        {
            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode: "PushChangeOilDrumInfo", pagecode: this.PageCode, powerName: "充值记录上传", pageTitle: this.PageTitle, creatNewIfNotExists: true);
            OperateLoger.InputMessage = JsonConvert.SerializeObject(rechargeRspInfo);
            OperateLoger.OperationResult = OperationResult.Success;

            var result = new ApiResult();

            OperationResult or = MoneyChangeContract.Recharge(rechargeRspInfo);
            //TODO:1.1.15更换油桶状态上报 向后台上报油桶更换结果@zyf
            //TODO:1.1.15APIOPERATERLOG表操作掉 然后油的序列号 把所属客户写好  这样就知道 这个油在哪个机器上销售了
            //throw new NotImplementedException();
            //OperationResult or = await OilSerialNumContract.ChangeOilDrumInfo(changeOilDrumInfo);

            //result.Data = changeOilDrumInfo;
            if (or.Succeeded == false)
            {
                result.ResultType = ApiResultType.error;//操作成功信息编号
                result.Message = or.Message;           //操作成功描述信息
                result.InnerMessage = or.Message;      //操作成功信息
            }
            else
            {
                result.ResultType = ApiResultType.sucess;
                result.Message = "操作成功";
                result.InnerMessage = "操作成功";
            }

            OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
            OperateLoger.OperationResult = result.ResultType == ApiResultType.sucess ? OperationResult.Success : new OperationResult(OperationResultType.Error, result.InnerMessage);
            await OperateLoger.SaveLogAsync();
            return Request.CreateResponse(result.ResultType == ApiResultType.sucess ? HttpStatusCode.OK : HttpStatusCode.BadRequest, result);
        }

    }
}
